package com.cman777.springc.sample.config.ratelimit;

import com.cman777.springc.ratelimiter.rule.Dimension;
import com.cman777.springc.ratelimiter.rule.RateRule;
import com.cman777.springc.ratelimiter.rule.RateRuleImporter;
import com.cman777.springc.sample.bean.po.RatelimitRule;
import com.cman777.springc.sample.service.RatelimitRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenzhicong
 * @time 2020/9/18 16:52
 */
@Component
public class RateRuleImporter4Mybatis implements RateRuleImporter {
    @Autowired
    private RatelimitRuleService ratelimitRuleService;

    @Override
    public List<RateRule> importRule() {
        List<RatelimitRule> ratelimitRules = ratelimitRuleService.selectEnabledRule();
        return ratelimitRules.stream().map(r->{
            RateRule rateRule = new RateRule();
            rateRule.setAlg(r.getAlg());
            rateRule.setLimitTimes(r.getLimitTimes());
            rateRule.setUnit(r.getUnit());
            Dimension dimension = new Dimension();
            dimension.setAttributes(r.getAttributes());
            dimension.setCollector(r.getCollector());
            rateRule.setDimension(dimension);
            rateRule.setVal(r.getVal());
            rateRule.setId(r.getId().toString());
            rateRule.setOrderNum(r.getOrderNum());
            return rateRule;
        }).collect(Collectors.toList());
    }
}
